package com.miao.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.miao.ucenter.feignClient.CheckCodeClient;
import com.miao.ucenter.mapper.XcUserMapper;
import com.miao.ucenter.model.dto.AuthParamsDto;
import com.miao.ucenter.model.dto.XcUserExt;
import com.miao.ucenter.model.po.XcUser;
import com.miao.ucenter.service.OuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

//密码方式验证方法
@Service("password_authservice")
public class passwordAuthImpl implements OuthService {

    @Autowired
    private XcUserMapper xcUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private CheckCodeClient checkCodeClient;

    @Override
    public XcUserExt excute(AuthParamsDto authParamsDto) {
        //远程调用验证码服务中的service对验证码进行验证
//        Boolean verify = checkCodeClient.verify(authParamsDto.getCheckcodekey(), authParamsDto.getCheckcode());
//        if(!verify){
//            throw new RuntimeException("验证码错误！");
//        }
        //解析得到用户名，查询数据库
        String username = authParamsDto.getUsername();
        LambdaQueryWrapper<XcUser> xcUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xcUserLambdaQueryWrapper.eq(XcUser::getUsername, username);
        XcUser xcUser = xcUserMapper.selectOne(xcUserLambdaQueryWrapper);
        if(null == xcUser) {
            throw new RuntimeException("用户不存在");
        }
        //校验密码（重写了DaoAuthenticationProvider类，后续没有校验密码，所以在这里校验密码）
        String password = xcUser.getPassword();
        boolean matches = passwordEncoder.matches(authParamsDto.getPassword(), password);
        if(!matches){
            throw new RuntimeException("密码错误");
        }

        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser, xcUserExt);
        return xcUserExt;

    }
}
